import org.jsecurity.crypto.hash.Md5Hash
import org.springframework.web.multipart.MultipartFile
import rowingmanager.domain.Rower
import rowingmanager.domain.Organization
import rowingmanager.domain.User
import rowingmanager.domain.JsecUserRoleRel
import rowingmanager.domain.Address
import rowingmanager.domain.Country
import rowingmanager.domain.JsecRole
import util.groovy.command.RowerCreateCommand

class TestController {
    def fileService 

    def registerOrganization = {
      def organization = new Organization()
      organization.address = new Address()
      return    [organization:organization,clist:Country.list()]
    }

    def save = {
      println "${params.inspect()}"
      def usr = new User()
      bindData(usr,params,[include:'email'],"user")
      usr.password = new Md5Hash(params.user.password).toHex()
      def organizationRole = JsecRole.findByName("rowingmanager.domain.Organization")
      if(!organizationRole){
        log.info("Creating role - rowingmanager.domain.Organization")
        organizationRole = new JsecRole(name:"rowingmanager.domain.Organization")
        organizationRole.save()
       }
      

      def address = new Address()
      bindData(address,params,[exclude:'country'],"address")
      address.country = Country.get(params.address.country)

      def org = new Organization(params['organization'])
      org.address = address
      org.addToUsers(usr)

      MultipartFile file = request.getFile('logo');
      if(!file.isEmpty())
        org.avatar = fileService.uploadAndGetImage(file,usr.email)
     if(org.save()) {
       new JsecUserRoleRel(user:usr,role:organizationRole).save()
       flash.message = "Organization [${org.title}] saved!"
       println "organization saved!"
       redirect(action:'registerOrganization',model:[organization:new Organization()])
     }
     else {
       println "didn't save!"
       if(org.hasErrors()) {
         org.errors.each { println it }
       }
       flash.email = usr?.email //save email in flash so the user doesn't have to type it again
       render(view:'registerOrganization',model:[organization:org,clist:Country.list()])

     }
    }


    def showOrganizations = {
        params.max = 5
        [organizations:Organization.list(params)]
    }

    def showSingle = {
        [organization:Organization.get(params.id)]
    }

    def showAvatar = {
        def org = Organization.get(params.id)  //todo: tukaj nastavi eager loading za avatarData
        if(!org || !org?.avatar?.imageData){
            response.sendError(404)
            return;
        }

      //  response.setContentType("image/jpeg")
        response.setContentLength(org.avatar.imageData.data.size())
        OutputStream out = response.getOutputStream()
        out.write(org.avatar.imageData.data)
        out.close()

    }

     def delete = {
        def org = Organization.get(params.id)
        def usr = User.findByOrganization(org)
        if(org && usr){
            log.info("params.id = "+params.id)
            log.info("org.title = "+org.title)
            def jsrole = JsecUserRoleRel.findByUser(usr)
            if(jsrole){
                jsrole.delete(flush:true)
                org.delete(flush:true)
                log.info("rowingmanager.domain.Organization removed!")
                render(view:"showOrganizations",model:[organizations:Organization.list()])
            }
            else{
                log.error("Could not remove organization")
            }
        }
        else
        log.error("Could not get organization with id "+params.id)

    }

    def registerRower = {

      [rower:new Rower(),organizations:Organization.findAllByType("rowing club"),clist:Country.list()]
    }

    def saveRower = {   RowerCreateCommand rower ->
      println(params.inspect())
      if(rower.validate()){
        println 'validates!'
        def newRower = rower.createRower(params.country)
        newRower.organization = Organization.get(params.organization)

       def rowerRole = JsecRole.findByName("Rower")
        if(!rowerRole){
        log.info("Creating role - Rower")
        rowerRole = new JsecRole(name:"Rower")
        rowerRole.save()
       }

        if(newRower.save()){
           new JsecUserRoleRel(user:newRower,role:rowerRole).save()
           render 'success we saved it'
        }else{
          newRower.errors.each {println it}
          render(view:'registerRower',model:[rower:newRower,clist:Country.list()])
        }
        
      }
      else
      {
        rower.errors.each {
          println it
        }

        render(view:'registerRower',model:[rower:rower])
      }
     //log.info(params.inspect())
    /* def rower = new Rower()
     bindData(rower,params,[exclude:'organization'])
     def org = Organization.get(params.organization)
     org.addToUsers(rower)
     if(rower.save()){
        log.info("Successfully created a rower")
        render(view:'registerRower',model:[rower:new Rower(),organizations:Organization.findAllByType("rowing club")])
      }
      else{
        rower.errors.each {println it}
        log.info("Failed to save new rower")
       render(view:'registerRower',model:[rower:rower])
      }*/
    }
}
